<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import { useUserStore } from '@/stores'
import { userUpdateAvatarService } from '@/api/user'

// 基于 store 的数据，初始化 imgUrl 的值
const userStore = useUserStore()
const imgUrl = ref(userStore.user.user_pic)

const uploadRef = ref()

// 选择图片后预览图片
const onSelectFile = (uploadFile) => {
  // 预览图片方法1
  // imgUrl.value = URL.createObjectURL(uploadFile.raw)
  // 预览图片方法2 - 基于 FileReader 读取图片预览
  // 会把图片转换成 base64 格式，方便跟接口接轨
  // 使用FileReader读取文件
  const reader = new FileReader()
  reader.onload = (e) => {
    // 读取完成后的回调
    // imgUrl.value = e.target.result
    // 不用参数 e 的话，可以直接用 reader 变量
    imgUrl.value = reader.result
    // console.log(imgUrl.value)
  }
  reader.onerror = () => {
    console.error('文件读取失败')
  }
  // 开始读取文件（转为Data URL）
  reader.readAsDataURL(uploadFile.raw)
}

// 上传图片
const onUpdateAvatar = async () => {
  // 发生请求到后端更新头像
  await userUpdateAvatarService(imgUrl.value)
  // userStore 重新渲染
  await userStore.getUser()
  // 提示用户
  ElMessage.success('头像更新成功')
}
</script>

<template>
  <PageContainer title="更换头像">
    <el-upload
    ref="uploadRef"
    class="avatar-uploader"
    :auto-upload="false"
    :show-file-list="false"
    :on-change="onSelectFile"
  >
    <img v-if="imgUrl" :src="imgUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>

  <br>
  <el-button @click="uploadRef.$el.querySelector('input').click()" type="primary" :icon="Plus" size="large">选择图片</el-button>
  <el-button @click="onUpdateAvatar" type="success" :icon="Upload" size="large">上传图片</el-button>
  </PageContainer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>